import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Space, Tag, Card, Breadcrumb, Form, Radio, Button, DatePicker, Table, Modal, message } from 'antd'
import { ExclamationCircleOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons'
import { ArticleStatus } from 'api/constants'
import { delArticle, getArticles } from 'api/article'
import defaultImg from 'assets/error.png'
import Channel from 'components/Channel'

export default class ArticleList extends Component {
  render() {
    const { per_page, page, total_count, results } = this.state.articles
    return (
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单结构 */}
        <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              {ArticleStatus.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item label='频道' name='channel_id'>
            <Channel beforeAdd={{ id: -1, name: '全部频道' }} />
          </Form.Item>

          <Form.Item label='日期' name='date'>
            <DatePicker.RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
        <h3>根据筛选条件共查询到 {total_count} 条结果：</h3>
        {/* rowKey 表格行唯一字段名，字符串类型 */}
        <Table
          columns={this.columns}
          dataSource={results}
          rowKey='id'
          pagination={{
            position: ['bottomCenter'],
            total: total_count,
            pageSize: per_page,
            current: page,
            onChange: this.onChange,
          }}
        />
      </Card>
    )
  }

  columns = [
    {
      title: '封面',
      render(item) {
        // 情况1：无图，渲染默认图片
        // 情况2：有图，渲染第一张图片
        return (
          <img
            src={item.cover.type === 0 ? defaultImg : item.cover.images[0]}
            title={item.title}
            alt={item.title}
            style={{ width: 100, height: 60, objectFit: 'cover' }}
          />
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = ArticleStatus.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <Space>
            <Button onClick={() => this.handleEdit(item.id)} type='primary' shape='circle' icon={<EditOutlined />} />
            <Button onClick={() => this.handleDelete(item.id)} type='primary' danger shape='circle' icon={<DeleteOutlined />} />
          </Space>
        )
      },
    },
  ]

  // 用于存放查询文章列表的所有的参数
  reqParams = {
    page: 1,
    per_page: 10,
  }

  state = {
    // 频道列表数据
    channels: [],
    articles: {},
  }

  handleEdit = (id) => {
    this.props.history.push(`/home/publish/${id}`)
  }

  handleDelete = (id) => {
    // 弹窗显示
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章？',
      onOk: async () => {
        // 发送请求，删除文章
        await delArticle(id)
        // 重新获取文章列表
        this.getArticleList()
        message.success('删除成功')
      },
    })
  }

  onChange = (page, pageSize) => {
    this.reqParams.page = page
    this.reqParams.per_page = pageSize
    this.getArticleList()
  }

  async getArticleList() {
    const res = await getArticles(this.reqParams)
    this.setState({
      articles: res.data,
    })
  }

  componentDidMount() {
    this.getArticleList()
  }

  onFinish = ({ status, channel_id, date }) => {
    console.log({ status, channel_id, date })
    // 状态
    this.reqParams.status = status !== -1 ? status : undefined
    // 频道
    this.reqParams.channel_id = channel_id !== -1 ? channel_id : undefined
    // 日期有两部分：开始日期和结束日期
    console.log('日期对象', date)
    // 开始日期
    this.reqParams.begin_pubdate = date ? date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined
    // 结束日期
    this.reqParams.end_pubdate = date ? date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined
    // 查询操作，需要让页码值重新为1
    this.reqParams.page = 1
    // 遍历过滤掉无效参数
    for (const key in this.reqParams) {
      if (this.reqParams[key] === undefined) {
        delete this.reqParams[key]
      }
    }
    // 发送请求前检查所有请求参数
    console.log('所有请求参数', this.reqParams)
    // 重新发送请求
    this.getArticleList()
  }
}
